import React from 'react'
import {
  View,
  StyleSheet,
  Text,
  Image,
  PermissionsAndroid,
  InteractionManager
} from 'react-native'
import { ScaleS, ScaleT, IS_ANDROID } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import { isEmptyObjectFn } from 'src/utils/JSTypeUtil'
import { AgreementCustom } from 'src/config/index'
import { ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { RNTOneLogin } from 'src/bridge/index'

/* redux */
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION,
  DO_REQUEST_AUTH_TOKEN_ACTION,
  DO_REQUEST_USERINFO_C_ACTION,
  DO_REQUEST_USERINFO_B_ACTION
} from 'src/store/actions/userinfo'
import {
  DO_REQUEST_MAIN_PAGE_C_ACTION,
  DO_REQUEST_MY_CENTER_NUMBERS_ACTION
} from 'src/pageC/mine/mine-page/store/action'
import { DO_REQUEST_MAIN_PAGE_B_ACTION } from 'src/pageB/main/main-page/store/action'

const mapActiontoProps = dispatch => ({
  updateUserInfoState (payload) {
    dispatch({
      type: UPDATE_USERINFO_ACTION,
      payload: {
        ...payload
      }
    })
  },
  doRequestAuthToken (payload) {
    const promise = DO_REQUEST_AUTH_TOKEN_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUserInfoC (payload) {
    const promise = DO_REQUEST_USERINFO_C_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUserInfoB (payload) {
    const promise = DO_REQUEST_USERINFO_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPageC (...payload) {
    const promise = DO_REQUEST_MAIN_PAGE_C_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMyCenterNumbersC (payload) {
    const promise = DO_REQUEST_MY_CENTER_NUMBERS_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPageB (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo }) => ({
    userinfo
  }),
  mapActiontoProps
)
class OneLogin extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      ...this.state,
      headerMode: 'none',
      display: true
    }
  }

  childRender () {
    const { display } = this.state
    if (!display) {
      return null
    }
    return (
      <View style={styles.container}>
        <View style={styles.tipsContent}>
          <Text style={styles.tips}>正在验证您的身份</Text>
          <Text style={[styles.tips, styles.tipsBot]}>请稍后…</Text>
        </View>
        <View style={styles.imgContainer}>
          <Image
            style={styles.image}
            source={require('@/imgC/login/star.png')}
          />
        </View>
      </View>
    )
  }

  componentDidMount () {
    InteractionManager.runAfterInteractions(() => {
      if (IS_ANDROID) {
        PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE
        )
          .then(data => {
            if (PermissionsAndroid.RESULTS.GRANTED === data) {
              this._oneLogin()
            } else {
              this.props.navigation.replace('VerifyCodeLogin')
            }
          })
          .catch(data => {
            console.info('oneLogin--->error-->', data)
          })
      } else {
        this._oneLogin()
      }
    })
  }

  _oneLogin = () => {
    console.log('RNTOneLogin')
    let dismissTimer = null
    // 延迟隐藏当前页面
    RNTOneLogin.sendMessage(AgreementCustom).then(res => {
      console.log(res)
      const { status, token, processID: processId, authCode } = res
      if (status === 200 && token && processId) {
        this.loginRequest({
          grant_type: 'one_login',
          token,
          processId,
          authCode
        })
      } else if (status === 300) {
        // 返回
        this.goBack()
      } else {
        dismissTimer && clearTimeout(dismissTimer)
        this.props.navigation.replace('VerifyCodeLogin')
      }
    })
    dismissTimer = setTimeout(() => {
      this.setState({ display: false })
      clearTimeout(dismissTimer)
    }, 2000)
  }

  loginRequest = params => {
    const {
      doRequestAuthToken,
      doRequestUserInfoC,
      doRequestUserInfoB,
      doRequestMainPageC,
      doRequestMyCenterNumbersC,
      doRequestMainPageB
    } = this.props
    ShowLoading()
    doRequestAuthToken({ params })
      .then(res => {
        console.log('getAuthTokenRequest', res)
        const { userId } = res
        params = { userId }
        return Promise.all([
          doRequestUserInfoC({ params }),
          doRequestUserInfoB({ params })
        ])
      })
      .then(([{ C }, { B }]) => {
        const {
          userinfo: { role },
          userId
        } = this.props
        // console.log('判断用户是否存在res', C, B)
        this.LoginSuccess = true // 清空state
        if (isEmptyObjectFn(role === 'C' ? C : B)) {
          // this.props.navigation.replace(`${role}FirstUserInfo`)
          return {}
        } else {
          // this.goBack()
          if (role === 'C') {
            return Promise.all([
              doRequestMainPageC({ params }),
              doRequestMyCenterNumbersC({ type: 'C', userId })
            ])
          } else {
            return doRequestMainPageB({ userId })
          }
        }
      })
      .then(() => {
        const {
          userinfo: { role, B, C }
        } = this.props
        // console.log('判断用户是否存在res', C, B)
        this.LoginSuccess = true // 清空state
        if (isEmptyObjectFn(role === 'C' ? C : B)) {
          this.props.navigation.replace(`${role}FirstUserInfo`)
        } else {
          this.goBack()
        }
      })
      .catch(() => {
        this.props.navigation.replace('VerifyCodeLogin')
      })
      .finally(() => {
        DismissLoading()
      })
  }
}

export default OneLogin

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'flex-start',
    backgroundColor: '#FFE400'
  },
  tipsContent: {
    marginTop: ScaleS(100),
    marginLeft: ScaleS(30)
  },
  tips: {
    fontSize: ScaleT(22),
    fontWeight: '500',
    color: 'rgba(68,68,68,1)'
  },
  tipsBot: {
    marginTop: ScaleS(20)
  },
  imgContainer: {
    width: '100%',
    marginTop: ScaleS(100),
    justifyContent: 'center',
    alignItems: 'center'
  },
  image: {
    resizeMode: 'cover'
  }
})
